# -*- coding: utf-8 -*-
from django.db import models

from django.contrib.auth.models import User

from projects.models import Project
from news.models import News
from cab.models import Snippet

FIELD_CHOICES = (
  ("nc", "news comments"),
  ("n", "news"),
  ("pc", "project comments"),
  ("pr", "project releases"),
  ("pm", "project of the month"),
  ("s", "snippets"),
  ("sc", "snippet comments"),
            )
            
d = {
  "news comments": "nc",
  "news": "n" , 
  "project comments": "pc",
  "project releases": "pr",
  "project of the month":  "pm",
  "snippets": "s",
  "snippet comments": "sc",
         }

CHOICES = {}
for k, v in d.iteritems():
    CHOICES[k] = v
    CHOICES[v] = k

class SubscriptionManager(models.Manager):
    def subscribed(self, user, kind, obj_id=None):
        return bool(self.filter(user=user, kind=kind, object_id=obj_id))
    
    def by_user(self, user):
        return self.filter(user=user)
    
    def by_kind(self, kind, obj_id=None):
        subs = self.filter(models.Q(object_id=obj_id)|models.Q(object_id=None),
                       kind=kind,)
        return subs


class Subscription(models.Model):
    """
    send ``user`` a notification (by mail) on
    events of a certain ``kind``. If ``object_id``
    is set, it will be used for filtering for some kinds:

      * "nc", "pc" only comments for news/project with id == object_id
      * "pr" only releases for project with id == object_id
    """
    user = models.ForeignKey(User)

    kind = models.CharField(max_length=5, choices=FIELD_CHOICES)
    
    object_id = models.PositiveIntegerField(null=True, blank=True)
    
    objects = SubscriptionManager()
    
    def get_name(self):
         retval = self.get_kind_display()
         if self.object_id:
             if self.kind == "pc":
                 return 'comments on project "%s"' % (
                                         Project.objects.get(pk=self.object_id))
             elif self.kind ==  "pr":
                 return 'releases of project "%s"' % (
                                         Project.objects.get(pk=self.object_id))
             elif self.kind == "nc":
                 return 'comments on news "%s"' % (
                                         News.objects.get(pk=self.object_id))             
             elif self.kind == "nc":
                 return 'comments on snippet "%s"' % (
                                         Snippet.objects.get(pk=self.object_id))             
         return retval
             

    def __unicode__(self):
        return "%s subscribed to %s" % (self.user, self.get_name())
